package com.example.newsmanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.newsmanager.common.Result;
import com.example.newsmanager.entity.Home;
import com.example.newsmanager.entity.News;
import com.example.newsmanager.entity.User;
import com.example.newsmanager.service.HomeService;
import com.example.newsmanager.service.NewsService;
import com.example.newsmanager.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private UserService userService;
    @Autowired
    private HomeService homeService;



    @GetMapping(value = "/list")
    public Result<Map<String,Object>> getAllNews(@RequestParam("pages") Integer pages,
                                                 @RequestParam(value = "newsType",defaultValue = "null") String newsType,
                                                 @RequestParam(value = "size",defaultValue = "8") Integer size){
        //List<News> newsList = newsService.getAllNewsWithAuthor();
        Page<News> page = new Page<>(pages,size);
        if(!newsType.equals("null")) {
            QueryWrapper<News> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("news_type", newsType).orderByDesc("publish_time");
            newsService.page(page, queryWrapper);
            System.out.println(newsType);
        }else {
            QueryWrapper<News> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.orderByDesc("publish_time");
            // 获取新闻列表
            newsService.page(page, queryWrapper1);
        }
        List<News> newsList = page.getRecords();
        // 获取用户昵称
        for (News news : newsList) {
            User user = userService.getById(news.getUserId());
            if (user != null) {
                news.setAuthor(user.getNickname());
                newsService.updateById(news);
            }
            if (news.getIntro()==null){
                news.setIntro(news.getNewsContent());
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("totals",page.getTotal());
        data.put("currentPages",page.getCurrent());
        data.put("pageNumber",page.getPages());
        data.put("rows",newsList);
        return Result.success(data);
    }



    @PostMapping("/publish")
    public Result<News> publishNews(@RequestBody News news,HttpServletRequest request){
        // 获取request中存储的用户信息
        User currentUser = (User) request.getAttribute("currentUser");
        if(currentUser == null){
            return Result.fail("登录状态失效");
        }
        if (news.getIntro()==null){
            news.setIntro(news.getNewsContent());
        }
        news.setUserId(currentUser.getUserId());
        news.setAuthor(currentUser.getNickname());
        news.setPublishTime(Timestamp.valueOf(LocalDateTime.now()));
        newsService.save(news);
        return Result.success(news,"上传成功");
    }

    @DeleteMapping(value = "/delete")
    public Result<?>News(@RequestParam String newsId){

        boolean result=newsService.removeById(newsId);
        if (result==true) {
            return Result.success(true);
        }
        else{
            return Result.fail();
        }
    }

    @PutMapping("/update")
    public Result<?>updateNews(@RequestBody News news){
        newsService.updateById(news);
        return Result.success(news);
    }

    @PostMapping("/pageupdate")
    public Result<?>homePageUpdate(@RequestParam Long homePageId,@RequestParam String currentPageId){

        News news = newsService.getById(currentPageId);
        Home indexNews = homeService.getById(homePageId);
        indexNews.setNewsId(news.getNewsId());
        indexNews.setCover(news.getCover());
        indexNews.setTitle(news.getTitle());
        homeService.updateById(indexNews);
        return Result.success("更新成功");
    }

    @GetMapping("/getOneById")
    public Result<?>getNewsById(@RequestParam(value = "id") String id){
        News news=newsService.getById(id);
        Integer number = news.getNumber();
        news.setNumber(++number);
        newsService.updateById(news);
        return Result.success(news);
    }

    @GetMapping("/userList")
    public Result<Map<String,Object>>getNewsById(@RequestParam("pages") Integer pages,
                                                 @RequestParam(value = "size",defaultValue = "8") Integer size,
                                                 HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
            return Result.success(newsService.getListById(currentUser.getUserId(),pages,size),"查询用户发布列表成功");
    }
    @GetMapping("/collectList")
    public Result<Map<String,Object>>getCollectNewsList(@RequestParam("pages") Integer pages,
                                                        @RequestParam(value = "size",defaultValue = "8") Integer size,
                                                        HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
        return Result.success(newsService.getCollectList(currentUser.getUserId(),pages,size),"获取当前用户收藏列表成功");
    }

    @GetMapping("/search")
    public Result<Map<String,Object>>searchNews(@RequestParam(value = "keyword",required = true) String keyword,
                                                @RequestParam(value = "pages")Integer pages,
                                                @RequestParam(value = "size",defaultValue = "8")Integer size){
        if (keyword.equals("")){
            log.info("空搜索");
            return Result.fail(203,"空搜索");
        }
        log.info("搜索成功");
        return Result.success(newsService.searchNews(keyword,pages,size),"搜索成功");
    }
    @GetMapping("/toplist")
    public Result<Map<String,Object>>topNewsList(@RequestParam(value = "pages")Integer pages,
                                                 @RequestParam(value = "size",defaultValue = "8")Integer size){
        return Result.success(newsService.getNewsListByNumber(pages,size),"获取热榜成功");
    }
//    @GetMapping(value="/list",params = {"userId","pages"})
//    public List<News> getMyAllNews(@RequestParam("userId") Integer userId ,@RequestParam("pages") Integer pages){
//        return newDsService.getMyAllNewsService(userId,pages);
//    }
//
//    @GetMapping(value="/list",params = {"newsType","pages"})
//    public List<News> getTypeAllNews(@RequestParam String newsType,@RequestParam Integer pages){
//        return newsService.getTypeAllNewsService(newsType,pages);
//    }
//    @GetMapping(value = "/type")
//    public Result<Map<String,Object>> getNewsByType(@RequestParam(value = "newsType",required = true) String newsType,
//                                                    @RequestParam(value = "pages",required = true) Integer pages){
//        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
//        Page<News> newsPage = new Page<>(pages,8);
//        queryWrapper.eq("news_type",newsType);
//        newsService.page(newsPage,queryWrapper);
//        Map<String,Object> data = new HashMap<>();
//        data.put("totals",newsPage.getTotal());
//        data.put("currentPages",newsPage.getCurrent());
//        data.put("pageNumber",newsPage.getPages());
//        data.put("rows",newsPage.getRecords());
//        return Result.success(data);
//    }
}
